package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	//lear1()
	lear7()

}

func lear1() {
	var c1, c2 chan int

	select {
	case n := <-c1:
		fmt.Println("received form c1:", n)
	case n := <-c2:
		fmt.Println("received form c2:", n)
	default:
		fmt.Println("No value received")

	}
}
func generator() chan int {
	out := make(chan int)

	go func() {
		i := 1
		for {
			time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond)
			out <- i
			i++
		}
	}()
	return out
}

func lear2() {
	var c1, c2 = generator(), generator()

	for {
		select {
		case n := <-c1:
			fmt.Println("received form c1:", n)
		case n := <-c2:
			fmt.Println("received form c2:", n)
		}
	}

}

func lear3() {
	var c1, c2 = generator(), generator()
	w := createWorker(0)
	for {
		select {
		case n := <-c1:
			w <- n
		case n := <-c2:
			w <- n
		}
	}

}
func lear4() {
	var c1, c2 = generator(), generator()
	w := createWorker(0)
	for {
		n := 0
		select {
		case n = <-c1:
		case n = <-c2:
		case w <- n:
		}
	}

}
func lear5() {
	var c1, c2 = generator(), generator()
	w := createWorker(0)
	n := 0
	hasValue := false
	for {

		select {
		case n = <-c1:
			hasValue = true
		case n = <-c2:
			hasValue = true
		case w <- n:
			if hasValue {
				// send to
			}
		}
	}

}
func lear6() {
	var c1, c2 = generator(), generator()
	var w = createWorker(0)
	n := 0
	hasValue := false
	for {
		var activeWorker chan int
		if hasValue {
			activeWorker = w
		}
		select {
		case n = <-c1:
			hasValue = true
		case n = <-c2:
			hasValue = true
		case activeWorker <- n:
			hasValue = false
		}
	}
}
func lear7() {
	var c1, c2 = generator(), generator()
	var w = createWorker(0)
	n := 0
	// 设置一个10秒的定时器
	timer := time.After(10 * time.Second)
	ticker := time.Tick(1200 * time.Millisecond)
	var values []int
	for {
		var activeWorker chan int
		var activeValue int
		if len(values) > 0 {
			activeWorker = w
			activeValue = values[0]
		}
		select {
		case n = <-c1:
			values = append(values, n)
		case n = <-c2:
			values = append(values, n)
		case activeWorker <- activeValue:
			values = values[1:]
		case <-time.After(900 * time.Millisecond):
			fmt.Println("timeout ! ")
		case <-ticker:
			fmt.Println("queue len = ", len(values))
		case <-timer:
			fmt.Println("Timeout reached after 10 seconds")
			return
		}
	}

}
func worker(id int, c chan int) {
	for n := range c {
		fmt.Printf("worker id %d received form  %d \n", id, n)
	}
}
func worker2(id int, c chan int) {
	for n := range c {
		randomWait := time.Duration(rand.Intn(1000)+500) * time.Millisecond
		time.Sleep(randomWait)
		fmt.Printf("worker2 id %d received form  %d \n", id, n)
	}
}
func createWorker(id int) chan int {
	c := make(chan int)
	go worker2(id, c)
	return c
}
